package com.hutao.medical.service.quality;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tools.ant.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hutao.medical.common.config.ConfigProperties;
import com.hutao.medical.common.util.Arith;
import com.hutao.medical.common.util.DateUtil;
import com.hutao.medical.common.util.HttpClientUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.constant.FunctionType;
import com.hutao.medical.mapper.quality.HospitalNoteMapper;
import com.hutao.medical.mapper.quality.MedicalFunctionMapper;
import com.hutao.medical.mapper.quality.MedicalQualityFunctionMapper;
import com.hutao.medical.mapper.quality.MedicalQualityMapper;
import com.hutao.medical.mapper.quality.MedicalQualityRecordMapper;
import com.hutao.medical.mapper.quality.MedicalRecordMapper;
import com.hutao.medical.mapper.quality.PointsStandardMapper;
import com.hutao.medical.pojo.quality.HospitalNote;
import com.hutao.medical.pojo.quality.MedicalFunction;
import com.hutao.medical.pojo.quality.MedicalQuality;
import com.hutao.medical.pojo.quality.MedicalQualityFunction;
import com.hutao.medical.pojo.quality.MedicalQualityRecord;
import com.hutao.medical.pojo.quality.MedicalRecord;
import com.hutao.medical.pojo.quality.PointsStandard;
import com.hutao.medical.pojo.vo.MedicalAjaxVo;
import com.hutao.medical.pojo.vo.MedicalRecordVo;
import com.hutao.medical.pojo.vo.QueryMedQuaTotalParam;

@Transactional
@Service
public class QualityService {

	@Autowired
	private PointsStandardMapper pointsStandardMapper;

	@Autowired
	private MedicalRecordMapper medicalRecordMapper;

	@Autowired
	private MedicalQualityRecordMapper medicalQualityRecordMapper;

	@Autowired
	private MedicalFunctionMapper medicalFunctionMapper;

	@Autowired
	private MedicalQualityMapper medicalQualityMapper;

	@Autowired
	private MedicalQualityFunctionMapper medicalQualityFunctionMapper;

	@Autowired
	private HospitalNoteMapper hospitalNoteMapper;

	@Autowired
	private ConfigProperties configProperties;

	/**
	 * 查询一级病案质控
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<PointsStandard> getFirstStandard() {
		return pointsStandardMapper.getFirstProject();
	}

	/**
	 * 查询病案质控
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<PointsStandard> getStandardList(Integer parentId) {
		return pointsStandardMapper.getProjectList(parentId);
	}

	/**
	 * 根据id查询PointsStandard
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public PointsStandard getPointsStandard(Integer id) {

		return pointsStandardMapper.selectByPrimaryKey(id);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public int addMedicalQuality(MedicalQuality medicalQuality, String firstGuid, String operator,
			Integer functionType) {
		MedicalFunction medicalFunction = null;
		if (medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(firstGuid, functionType) > 0) {
			medicalFunction = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid, functionType);
		} else {
			medicalFunction = new MedicalFunction();
			medicalFunction.setCreateTime(new Date());
			medicalFunction.setFirstGuid(firstGuid);
			medicalFunction.setFunctionTypeId(functionType);
			medicalFunction.setStatus(1);
			medicalFunctionMapper.insert(medicalFunction);
		}

		medicalQualityMapper.insert(medicalQuality);

		MedicalQualityFunction medicalQualityFunction = new MedicalQualityFunction();
		medicalQualityFunction.setQualityName(operator);
		medicalQualityFunction.setQualityTime(new Date());
		medicalQualityFunction.setCreateTime(new Date());
		medicalQualityFunction.setStatus(1);
		medicalQualityFunction.setMedicalFunctionId(medicalFunction.getId());
		medicalQualityFunction.setMedicalQualityId(medicalQuality.getId());
		medicalQualityFunctionMapper.insert(medicalQualityFunction);
		return 0;

	}

	// @Transactional(readOnly = true)
	// public List<Map<String, Object>> getSingleMedList(String firstGuid) {
	// List<Map<String, Object>> list =
	// medQualityControlMapper.getSingleMedList(firstGuid);
	// if (list != null && list.size() > 0) {
	// for (Map<String, Object> map : list) {
	// Integer firstProId = (Integer) map.get("firstProId");
	// Integer secondProId = (Integer) map.get("secondProId");
	// Integer thirdProId = (Integer) map.get("thirdProId");
	// PointsStandard firstPointsStandard =
	// pointsStandardMapper.selectByPrimaryKey(firstProId);
	// map.put("firstPro", firstPointsStandard.getProject());
	// PointsStandard secondPointsStandard =
	// pointsStandardMapper.selectByPrimaryKey(secondProId);
	// map.put("secondPro", secondPointsStandard.getProject());
	// PointsStandard thirdPointsStandard =
	// pointsStandardMapper.selectByPrimaryKey(thirdProId);
	// map.put("thirdPro", thirdPointsStandard.getProject());
	// }
	// }
	// return list;
	// }

	@Transactional(propagation = Propagation.REQUIRED)
	public void checkQua(Integer qcaId, Integer status, String operator) {
		MedicalQualityFunction medicalQualityFunction = new MedicalQualityFunction();
		medicalQualityFunction.setId(qcaId);
		medicalQualityFunction.setStatus(2);
		medicalQualityFunction.setCheckMan(operator);
		medicalQualityFunction.setCheckTime(new Date());
		medicalQualityFunctionMapper.updateByPrimaryKeySelective(medicalQualityFunction);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateMedQuaCon(MedicalQuality medicalQuality) {
		medicalQualityMapper.updateByPrimaryKeySelective(medicalQuality);
	}

	/**
	 * 质控统计
	 * 
	 * @param params
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> getMedQuaStaticMapList(MedicalRecordVo medicalRecordVo) {
		List<Map<String, Object>> list = new ArrayList<>();
		List<Map<String, Object>> officeList = medicalRecordMapper.selectQualityConditionByOfficeName(medicalRecordVo);
		if (CollectionUtils.isNotEmpty(officeList)) {
			Map<String, Object> newMap = null;
			for (Map<String, Object> map : officeList) {
				newMap = new LinkedHashMap<>();
				newMap.put("officeName", map.get("officeName"));
				long qualityCount = (long) map.get("qualityCount");
				newMap.put("qualityCount", qualityCount);
				double firstLevelCount = 0.0;
				double secondLevelCount = 0.0;
				double thirdLevelCount = 0.0;
				double qcPointCount = 0.0;
				String uniqueKeys = (String) map.get("uniqueKeys");
				if (StringUtils.isNotEmpty(uniqueKeys)) {
					for (String uniqueKey : uniqueKeys.split(",")) {
						Map<String, Object> quaMap = medicalRecordMapper.selectQuaPointsByUniqueKey(uniqueKey);
						if (quaMap != null && quaMap.size() > 0) {
							double qcPoints = (double) quaMap.get("qcPoints");
							qcPointCount += qcPoints;
							String level = (String) quaMap.get("level");
							if (level.equals("甲")) {
								firstLevelCount++;
							} else if (level.equals("乙")) {
								secondLevelCount++;
							} else {
								thirdLevelCount++;
							}
						}

					}
				}
				newMap.put("firstLevelCount", firstLevelCount);
				newMap.put("firstLevelRate", Arith.div(firstLevelCount, qualityCount, 4) * 100);
				newMap.put("secondLevelCount", secondLevelCount);
				newMap.put("secondLevelRate", Arith.div(secondLevelCount, qualityCount, 4) * 100);
				newMap.put("thirdLevelCount", thirdLevelCount);
				newMap.put("thirdLevelRate", Arith.div(thirdLevelCount, qualityCount, 4) * 100);
				newMap.put("qcPointsCount", qcPointCount);
				list.add(newMap);

			}
		}

		return list;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public HospitalNote getHospitalNote(String firstGuid, Integer functionTypeId) {

		HospitalNote hospitalNote = new HospitalNote();
		MedicalFunction medicalFunction = null;
		if (hospitalNoteMapper.isExistHospitalNote(firstGuid) > 0) {
			hospitalNote = hospitalNoteMapper.getHospitalNoteByFirstGuid(firstGuid);
			if (medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(firstGuid, functionTypeId) > 0) {
				medicalFunction = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid, functionTypeId);
			} else {
				medicalFunction = new MedicalFunction();
				medicalFunction.setCreateTime(new Date());
				medicalFunction.setFirstGuid(firstGuid);
				medicalFunction.setFunctionTypeId(functionTypeId);
				medicalFunction.setStatus(1);
				medicalFunctionMapper.insert(medicalFunction);
			}
			return hospitalNote;
		}
		Map<String, String> param = new HashMap<>();
		param.put("firstGuid", firstGuid);

		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getGetMedRecordByFirstGuidPath(),
				param);
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		Map<String, Object> dataMap = (Map<String, Object>) result.getData();
		if (MapUtils.isNotEmpty(dataMap)) {
			hospitalNote.setFirstGuid(firstGuid);
			hospitalNote.setName(dataMap.get("NAME") == null ? null : (String) dataMap.get("NAME"));
			hospitalNote.setCreateDate(new Date());
			hospitalNote.setMrId(dataMap.get("mrId") == null ? null : (String) dataMap.get("mrId"));
			hospitalNote.setOnlyId(dataMap.get("onlyId") == null ? null : (String) dataMap.get("onlyId"));
			hospitalNote.setIdNumber(dataMap.get("idCard") == null ? null : (String) dataMap.get("idCard"));
			hospitalNote
					.setVisitNumber(dataMap.get("visit_number") == null ? null : (Integer) dataMap.get("visit_number"));
			hospitalNote.setOutHospitalOfficeCode(
					dataMap.get("officeCode") == null ? null : (String) dataMap.get("officeCode"));
			hospitalNote.setOutHospitalOfficeName(
					dataMap.get("outOfficeName") == null ? null : (String) dataMap.get("outOfficeName"));
			hospitalNote.setOutHospitalTypeCode(
					dataMap.get("outHospitalTypeId") == null ? null : (Integer) dataMap.get("outHospitalTypeId") + "");
			hospitalNote.setOutHospitalType(
					dataMap.get("outHospitalType") == null ? null : (String) dataMap.get("outHospitalType"));
			hospitalNote.setBirthday(
					dataMap.get("birthday") == null ? null : DateUtil.strToDate((String) dataMap.get("birthday")));
			hospitalNote.setOutHospitalDate(dataMap.get("outHospitalDate") == null ? null
					: DateUtil.strToDate((String) dataMap.get("outHospitalDate")));
			hospitalNoteMapper.insert(hospitalNote);

		}
		if (medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(firstGuid, FunctionType.quality) > 0) {
			medicalFunction = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid,
					FunctionType.quality);
		} else {
			medicalFunction = new MedicalFunction();
			medicalFunction.setCreateTime(new Date());
			medicalFunction.setFirstGuid(firstGuid);
			medicalFunction.setFunctionTypeId(functionTypeId);
			medicalFunction.setStatus(1);
			medicalFunctionMapper.insert(medicalFunction);
		}

		return hospitalNote;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public MedicalRecord addMedicalRecord(MedicalRecord medicalRecord) {
		String uniqueKey = medicalRecord.getUniqueKey();

		HospitalNote hospitalNote = new HospitalNote();
		if (hospitalNoteMapper.isExistHospitalNote(uniqueKey) > 0) {
			hospitalNote = hospitalNoteMapper.getHospitalNoteByFirstGuid(uniqueKey);

		}
		Map<String, String> param = new HashMap<>();
		param.put("firstGuid", uniqueKey);

		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getGetMedRecordByFirstGuidPath(),
				param);
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		Map<String, Object> dataMap = (Map<String, Object>) result.getData();
		if (MapUtils.isNotEmpty(dataMap)) {
			hospitalNote.setFirstGuid(uniqueKey);
			hospitalNote.setName(dataMap.get("NAME") == null ? null : (String) dataMap.get("NAME"));
			hospitalNote.setCreateDate(new Date());
			hospitalNote.setMrId(dataMap.get("mrId") == null ? null : (String) dataMap.get("mrId"));
			hospitalNote.setOnlyId(dataMap.get("onlyId") == null ? null : (String) dataMap.get("onlyId"));
			hospitalNote.setIdNumber(dataMap.get("idCard") == null ? null : (String) dataMap.get("idCard"));
			hospitalNote.setOutHospitalOfficeCode(
					dataMap.get("officeCode") == null ? null : (String) dataMap.get("officeCode"));
			hospitalNote.setOutHospitalOfficeName(
					dataMap.get("outHospitalType") == null ? null : (String) dataMap.get("outOfficeName"));
			hospitalNote
					.setVisitNumber(dataMap.get("visit_number") == null ? null : (Integer) dataMap.get("visit_number"));
			hospitalNote.setOutHospitalTypeCode(
					dataMap.get("outHospitalTypeId") == null ? null : (Integer) dataMap.get("outHospitalTypeId") + "");
			hospitalNote.setBirthday(
					dataMap.get("birthday") == null ? null : DateUtil.strToDate((String) dataMap.get("birthday")));
			hospitalNote.setOutHospitalDate(dataMap.get("outHospitalDate") == null ? null
					: DateUtil.strToDate((String) dataMap.get("outHospitalDate")));
			hospitalNoteMapper.insert(hospitalNote);
		}
		if (StringUtils.isNoneEmpty(uniqueKey)) {
			int flag = medicalRecordMapper.getMedicalRecordCountByUniqueKey(uniqueKey);
			if (flag > 0) {
				return medicalRecordMapper.selectByUniqueKey(uniqueKey);
			} else {

				medicalRecordMapper.insertSelective(medicalRecord);
				MedicalQualityRecord medicalQualityRecord = new MedicalQualityRecord();
				medicalQualityRecord.setStatus(1);
				medicalQualityRecord.setMedicalRecordId(medicalRecord.getId());
				medicalQualityRecord.setUniqueKey(uniqueKey);
				medicalQualityRecord.setOperator(medicalRecord.getOperator());
				medicalQualityRecordMapper.insertSelective(medicalQualityRecord);
				return medicalRecord;
			}
		}
		return medicalRecord;
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> selectQualityListByUniqueKey(String uniqueKey) {
		return medicalRecordMapper.selectListByUniqueKey(uniqueKey);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> selectQualityListByKeywords(MedicalRecordVo medicalRecordVo) {
		return medicalRecordMapper.selectQualityListByKeywords(medicalRecordVo);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> exportQualityListToExcel(MedicalRecordVo medicalRecordVo) {
		return medicalRecordMapper.exportQualityListToExcel(medicalRecordVo);
	}

	@Transactional(readOnly = true)
	public int selectQualityListCountByKeywords(MedicalRecordVo medicalRecordVo) {
		return medicalRecordMapper.selectQualityListCountByKeywords(medicalRecordVo);
	}

	// @Transactional(propagation = Propagation.REQUIRED)
	// public int deleteQuality(Integer mqcId) {
	//
	// return medQualityControlMapper.deleteByPrimaryKey(mqcId);
	// }

	@Transactional(propagation = Propagation.REQUIRED)
	public int deleteQuality(Integer mqcId, Integer mqId) {
		medicalQualityFunctionMapper.deleteByPrimaryKey(mqcId);
		medicalQualityMapper.deleteByPrimaryKey(mqId);
		return 1;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public int completeQuality(String uniqueKey, String user) throws UnsupportedEncodingException {
		Map<String, String> map = new HashMap<>();
		map.put("treatmentGuid", uniqueKey);
		map.put("userId", URLEncoder.encode(user, "UTF-8"));
		HttpClientUtil.doPost(configProperties.getMedicalManage().getAddQualityTracePath(), map);
		// Result result=JsonUtils.jsonToPojo(userJson, Result.class);
		MedicalFunction medicalFunction = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(uniqueKey,
				FunctionType.quality);
		if (medicalFunction != null) {
			medicalFunction.setStatus(2);
			medicalFunctionMapper.updateByPrimaryKeySelective(medicalFunction);
		}
		return 1;

	}

	@Transactional(readOnly = true)
	public Map<String, Object> selectQualityByMqcId(Integer mqcId) {
		return medicalRecordMapper.selectQualityByMqcId(mqcId);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> getMedQualityByFirstGuidAndFunType(String firstGuid, Integer medicalFunctionType) {
		return medicalQualityMapper.getMedQualityByFirstGuidAndFunType(firstGuid, medicalFunctionType);
	}

	// ------------------------------------------------------------

	/**
	 * 查询质控详情
	 * 
	 * @param medicalRecordVo
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> getMedicalQualityFunctionList(MedicalRecordVo medicalRecordVo) {
		return medicalQualityMapper.getMedicalQualityFunctionList(medicalRecordVo);
	}

	/**
	 * 查询质控详情总数
	 * 
	 * @param medicalRecordVo
	 * @return
	 */
	@Transactional(readOnly = true)
	public int getMedicalQualityFunctionCount(MedicalRecordVo medicalRecordVo) {
		return medicalQualityMapper.getMedicalQualityFunctionCount(medicalRecordVo);
	}

	/**
	 * 查询首页质控信息
	 * 
	 * @param medicalRecordVo
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> getFirstMedQuaLityList(MedicalRecordVo medicalRecordVo) {
		return medicalQualityMapper.getFirstMedQuaLityList(medicalRecordVo);
	}

	/**
	 * 查询首页质控信息总条数
	 * 
	 * @param medicalRecordVo
	 * @return
	 */
	@Transactional(readOnly = true)
	public int getFirstMedQuaLityCount(MedicalRecordVo medicalRecordVo) {
		return medicalQualityMapper.getFirstMedQuaLityCount(medicalRecordVo);
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> queryQualityDefect(QueryMedQuaTotalParam param) {
		List<Map<String, Object>> list = medicalQualityMapper.getMedicalDefaultTotalRateByOutTime(param);
		if(CollectionUtils.isEmpty(list)) {
			return new ArrayList<>();
		}
		
		for (Map<String, Object> map : list) {
			String officeName = (String)map.get("officeName");
			param.setOutHospitalOffice(officeName);
			List<Map<String,Object>> officeList = medicalQualityMapper.getMedicalOfficeError(param);
			for (Map<String, Object> map2 : officeList) {
				int  pointId= (int) map2.get("projectId");
				param.setPointId(pointId);
				List<Map<String,Object>> map3 = medicalQualityMapper.getMedicalMrIdError(param);
				map2.put("mrProject", map3);
			}
			param.setPointId(null);
			map.put("officeProject", officeList);
		}
		
		
		return list;
	}

	// @Transactional(readOnly = true)
	// public Map<String,Object> queryQualityDefect(QueryMedQuaTotalParam param){
	// Map<String,Object> map = new HashMap<>();
	// List<Map<String,Object>> medicalDefaultMapList=
	// medicalQualityMapper.getMedicalDefaultTotalRateByOutTime(param);
	// List<String> officeNameList = new ArrayList<>();
	// List<Long> oneList = new ArrayList<>();
	// List<Long> twoList = new ArrayList<>();
	// List<Long> threeList = new ArrayList<>();
	// List<Long> fourList = new ArrayList<>();
	// List<Long> fiveList = new ArrayList<>();
	// List<Long> sixList = new ArrayList<>();
	// for (Map<String, Object> medicalDefaultMap : medicalDefaultMapList) {
	// //{officeName=心胸外科病区, six=0, four=1, one=1, two=0, three=1, five=0}
	//
	//
	// if(medicalDefaultMap.get("officeName")!=null){
	// officeNameList.add((String)medicalDefaultMap.get("officeName"));
	// }
	// if(medicalDefaultMap.get("one")!=null){
	// long oneCount =(long)medicalDefaultMap.get("one");
	// oneList.add(oneCount==0?null:oneCount);
	// }
	// if(medicalDefaultMap.get("two")!=null){
	// long twoCount =(long)medicalDefaultMap.get("two");
	// twoList.add(twoCount==0?null:twoCount);
	// }
	// if(medicalDefaultMap.get("three")!=null){
	// long threeCount =(long)medicalDefaultMap.get("three");
	// threeList.add(threeCount==0?null:threeCount);
	// }
	// if(medicalDefaultMap.get("four")!=null){
	// long fourCount =(long)medicalDefaultMap.get("four");
	// fourList.add(fourCount==0?null:fourCount);
	// }
	// if(medicalDefaultMap.get("five")!=null){
	// long fiveCount =(long)medicalDefaultMap.get("five");
	// fiveList.add(fiveCount==0?null:fiveCount);
	// }
	// if(medicalDefaultMap.get("six")!=null){
	// long sixCount =(long)medicalDefaultMap.get("six");
	// sixList.add(sixCount==0?null:sixCount);
	// }
	//
	// map.put("officeList", officeNameList);
	// map.put("oneList", oneList);
	// map.put("twoList", twoList);
	// map.put("threeList", threeList);
	// map.put("fourList", fourList);
	// map.put("fiveList", fiveList);
	// map.put("sixList", sixList);
	// map.put("totalSize", medicalDefaultMapList.size());
	// }
	// return map;
	// }

	/*
	 * @Transactional(readOnly = true) public List<Map<String,Object>>
	 * queryQualityDefect(QueryMedQuaTotalParam param){ List<Map<String,Object>>
	 * list=new ArrayList<>(); List<Map<String,Object>> firstProList =
	 * medicalQualityMapper.queryQualityGrandpaDefectProject(param); for
	 * (Map<String, Object> firstMap : firstProList) { Integer firstProId =
	 * (Integer) firstMap.get("firstProId"); param.setFirstProId(firstProId);
	 * List<Map<String,Object>>
	 * secondProList=medicalQualityMapper.queryQualityFatherDefectProject(param);
	 * int firstRowSpan=0; for (Map<String, Object> secondProMap : secondProList) {
	 * Integer secondProId = (Integer) secondProMap.get("secondProId");
	 * param.setSecondProId(secondProId); List<Map<String,Object>> thirdProList =
	 * medicalQualityMapper.queryQualitySonDefectProject(param);
	 * secondProMap.put("thirdProList", thirdProList);
	 * secondProMap.put("secondRowSpan",thirdProList.size());
	 * firstRowSpan+=thirdProList.size(); } firstMap.put("firstRowSpan",
	 * firstRowSpan); firstMap.put("secondProList", secondProList);
	 * list.add(firstMap); }
	 * 
	 * return list; }
	 */
	/*
	 * @Transactional(readOnly = true) public List<Map<String,Object>>
	 * queryQualityGrandpaDefectProject(QueryMedQuaTotalParam param){ return
	 * medicalQualityMapper.queryQualityGrandpaDefectProject(param); }
	 */
	/*
	 * @Transactional(readOnly = true) public List<Map<String,Object>>
	 * queryQualityFatherDefectProject(int id){ return
	 * medicalQualityMapper.queryQualityFatherDefectProject(id); }
	 * 
	 * @Transactional(readOnly = true) public List<Map<String,Object>>
	 * queryQualitySonDefectProject(int id){ return
	 * medicalQualityMapper.queryQualitySonDefectProject(id); }
	 */

	@Transactional(readOnly = true)
	public Map<String, Object> getMedRecordQualityRate(MedicalAjaxVo medicalAjaxVo) {
		Map<String, String> params = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		// 参数为空直接返回
		if (medicalAjaxVo == null) {
			return map;
		}
		//
		if (medicalAjaxVo.getOutHospitalOfficeId() != null) {
			params.put("outHospitalOfficeId", medicalAjaxVo.getOutHospitalOfficeId() + "");
		}
		if (medicalAjaxVo.getOutHospitalStartDate() != null) {
			params.put("outHospitalStartDate",
					DateUtils.format(medicalAjaxVo.getOutHospitalStartDate(), "yyyy-MM-dd HH:mm:ss"));
		}
		if (medicalAjaxVo.getOutHospitalEndDate() != null) {
			params.put("outHospitalEndDate",
					DateUtils.format(medicalAjaxVo.getOutHospitalEndDate(), "yyyy-MM-dd HH:mm:ss"));
		}

		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getMedicalOutHospitalNumPath(),
				params);
		if (StringUtils.isEmpty(userJson)) {
			return map;
		}
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		if (result.isSuccess()) {
			List<Map<String, Object>> outHospitanNumMapList = (List<Map<String, Object>>) result.getData();
			int outHospitalTotalCount = 0;
			int qualityTotalCount = 0;
			for (Map<String, Object> outHospitanNumMap : outHospitanNumMapList) {
				// {code=410601, officeId=345, name=妇科病区, outHospitalCount=1}
				int levelA = 0;
				int levelB = 0;
				int levelC = 0;
				double qcPoints = 0.0;
				String code = (String) outHospitanNumMap.get("code");
				int outHospitalCount = (int) outHospitanNumMap.get("outHospitalCount");
				outHospitalTotalCount += outHospitalCount;

				List<String> firstGuidList = medicalQualityMapper.getFirstGuidListByOfficeCode(code);
				int qualityCount = firstGuidList.size();
				qualityTotalCount += qualityCount;
				outHospitanNumMap.put("qualityCount", qualityCount);
				if (CollectionUtils.isNotEmpty(firstGuidList)) {
					for (String firstGuid : firstGuidList) {
						String qcPointStr = medicalQualityMapper.getQcPointsByFirstGuid(firstGuid);
						qcPoints = StringUtils.isEmpty(qcPointStr) ? 0.0 : Double.parseDouble(qcPointStr);
						System.out.println(qcPoints);
						if (qcPoints <= 15) {
							levelA++;
						} else if (qcPoints > 15 && qcPoints <= 30) {
							levelB++;
						} else {
							levelC++;
						}
					}
				}
				outHospitanNumMap.put("qualityRate", this.calcateRate(qualityCount, outHospitalCount));
				outHospitanNumMap.put("levelACount", levelA);
				outHospitanNumMap.put("levelARate", this.calcateRate(levelA, qualityCount));
				outHospitanNumMap.put("levelBCount", levelB);
				outHospitanNumMap.put("levelBRate", this.calcateRate(levelB, qualityCount));
				outHospitanNumMap.put("levelCCount", levelC);
				outHospitanNumMap.put("levelCRate", this.calcateRate(levelC, qualityCount));

			}
			map.put("outHospitalTotalCount", outHospitalTotalCount);
			map.put("qualityTotalCount", qualityTotalCount);
			map.put("qualityTotalRate", this.calcateRate(qualityTotalCount, outHospitalTotalCount));
			map.put("qualityList", outHospitanNumMapList);
		} else {
			return map;
		}
		return map;

	}
	
	
	public void generateQualityErrorExcel(OutputStream out, String title, String[] header,List<Map<String,Object>> qualityErrorList) {
		// 创建一个工作薄
				HSSFWorkbook workbook = null;
				try {

					// 创建一个工作薄
					workbook = new HSSFWorkbook();
					// 创建一个sheet页
					HSSFSheet sheet = workbook.createSheet();
					// 设置sheet页的列宽
					sheet.setDefaultColumnWidth(25);

					// 设置标题样式
					HSSFCellStyle titleStyle = workbook.createCellStyle();
					// 设置字体居中显示
					titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					// 设置标题字体
					HSSFFont titleFont = workbook.createFont();
					titleFont.setFontHeightInPoints((short) 25);
					titleStyle.setFont(titleFont);

					// 产生标题
					HSSFRow row = sheet.createRow(0);
					HSSFCell cell = row.createCell(0);
					cell.setCellStyle(titleStyle);
					cell.setCellValue(title);
					// 合并单元格
					sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, header.length - 1));

					// 表头样式
					HSSFCellStyle headStyle = workbook.createCellStyle();
					headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
					// 设置填充模式
					headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

					// 设置字体居中
					headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
					headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
					headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
					headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
					
					//内容样式
					HSSFCellStyle contentStyle = workbook.createCellStyle();
					// 设置字体居中
					contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
					contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
					contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
					contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
					contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
					
					
					// 设置字体样式
					HSSFFont headFont = workbook.createFont();
					headFont.setColor(HSSFColor.LIGHT_ORANGE.index);
					headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置字体粗细
					headFont.setFontHeightInPoints((short) 16);
					headStyle.setFont(headFont);
					// 创建第二行，生成表格的表头行
					row = sheet.createRow(1);// 第二行
					for (int i = 0; i < header.length; i++) {
						cell = row.createCell(i);// 从第一列开始
						cell.setCellStyle(headStyle);// 设置列的样式
						cell.setCellValue(header[i]);
					}
					//{project=有涂改或伪造行为, pointId=20001, projectNum=1, officeProject=[{officeNum=1, mrProject=[{firstGuid=88f44d95b3d843c68d3a39ecd3405af5, mrId=D382, visitNumber=25}], outOfficeName=重症监护内科病区}]}
					int index=0;
					for(int i=0;i<qualityErrorList.size();i++) {
						Map<String,Object> firstLevelMap = qualityErrorList.get(i);
						List<Map<String,Object>> officeProjectList = (List<Map<String, Object>>) firstLevelMap.get("officeProject");
						long projectNum = firstLevelMap.get("totalNum")==null?0:(long)firstLevelMap.get("totalNum");
						// 合并单元格
						System.out.println(index+2+"---"+(index+1+(int)projectNum));
						sheet.addMergedRegion(new CellRangeAddress(index+2, index+1+(int)projectNum, 0, 0));
						sheet.addMergedRegion(new CellRangeAddress(index+2, index+1+(int)projectNum, 1, 1));
						for(int j=0;j<officeProjectList.size();j++) {
							Map<String,Object> officeMap = officeProjectList.get(j);
							//{officeNum=1, mrProject=[{firstGuid=88f44d95b3d843c68d3a39ecd3405af5, mrId=D382, visitNumber=25}], outOfficeName=重症监护内科病区}
							long officeNum = officeMap.get("projectNum")==null?0:(long)officeMap.get("projectNum");
							List<Map<String,Object>> mrList = (List<Map<String, Object>>) officeMap.get("mrProject");
							// 合并单元格
							System.out.println(index+2+"-------"+ (index+1+(int)officeNum));
							sheet.addMergedRegion(new CellRangeAddress(index+2, index+1+(int)officeNum, 2, 2));
							sheet.addMergedRegion(new CellRangeAddress(index+2, index+1+(int)officeNum, 3, 3));
							for (int k = 0; k < mrList.size(); k++) {
								Map<String,Object> mrMap = mrList.get(k);
								row = sheet.createRow(2+index);// 第二行
								
									cell = row.createCell(0);
									cell.setCellStyle(contentStyle);
									cell.setCellValue((String)firstLevelMap.get("officeName"));
									cell = row.createCell(1);
									cell.setCellStyle(contentStyle);
									cell.setCellValue(projectNum);
								
									cell = row.createCell(2);
									cell.setCellStyle(contentStyle);
									cell.setCellValue((String)officeMap.get("projectName"));
									
									cell = row.createCell(3);
									cell.setCellStyle(contentStyle);
									cell.setCellValue(officeNum);
							
									cell = row.createCell(4);
									cell.setCellStyle(contentStyle);
									cell.setCellValue((String)mrMap.get("mrId"));
									
									cell = row.createCell(5);
									cell.setCellStyle(contentStyle);
									cell.setCellValue((int)mrMap.get("visitNumber"));
									
									cell = row.createCell(6);
									cell.setCellStyle(contentStyle);
									cell.setCellValue((String)mrMap.get("med_control_desc"));
								index++;
							}
						}
		
					}
					

					workbook.write(out);
					out.flush();
					out.close();
					workbook.close();

				} catch (Exception e) {
					e.printStackTrace();
				}

	}
	
	
	

	/**
	 * 计算数据
	 * 
	 * @param numA
	 * @param numB
	 * @return
	 */
	public String calcateRate(int numA, int numB) {

		DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
		if (numB == 0) {
			return "0.00";
		}
		String num = df.format((float) numA / numB * 100);// 返回的是String类型
		return num;
	}

}
